#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QTime>
#include <QFile>
#include <QCoreApplication>
#include <QTextCodec>
#include <QTimer>
#include <QMessageBox>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 禁用最大化按钮和禁止调节窗口大小
    setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);
    setFixedSize(this->width(), this->height());

    // 计时器
    m_pTimer = new QTimer(this);
    connect(m_pTimer,SIGNAL(timeout()),this,SLOT(handleTimeout()));
    connect(ui->pushButton,&QPushButton::clicked,[=](){
        this->readList();
        if(code==0) {
            if(m_pTimer->isActive()){
                ui->pushButton->setText("开始");
                m_pTimer->stop();
            } else {
                ui->pushButton->setText("停止");
                m_pTimer->start(50);
            }
        } else if(code==1) {
            QMessageBox::critical(this,"出错了","请将data.txt人员名单放到程序同级目录下\n文件格式：一行一个姓名，多个姓名用换行符分割");
        } else if(code==2) {
            QMessageBox::critical(this,"出错了","读取文件出错！");
        }
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleTimeout() {
    QTime time = QTime::currentTime();
    qsrand(time.msec()+time.second()*1000);
    int num = qrand() % list.size();
    QString str = list.at(num);
    ui->label->setText(str);
}

//读取人员名单函数
void MainWindow::readList() {
    // 获取程序当前运行目录
    QString filePath = QCoreApplication::applicationDirPath();
    QFile file(filePath + "/data.txt");
    if(!file.exists()) {
        code = 1;
    } else if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        code = 2;
    } else {
        code = 0;
        QByteArray bytes = file.readAll();
        QTextCodec *codec = QTextCodec::codecForName("GBK");
        QString content = codec->toUnicode(bytes);
        list = content.split("\n");
    }
}
